package linkedList.分离合并;

import linkedList.BaseLinkedListTest;
import po.ListNode;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName 奇偶链表328.java
 * @Description TODO https://leetcode-cn.com/problems/odd-even-linked-list/
 * @createTime 2021年03月15日 13:34:00
 */
public class 奇偶链表328 extends BaseLinkedListTest {
    /**
     * todo 1. 按照奇数位和偶数位分离链表 2. 将偶数位链表拼接在奇数位链表后面
     */
    public static ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null) {
            return head;

        }
        //奇数位链表
        ListNode oddNodeList = new ListNode(0);
        //偶数位链表
        ListNode evenNodeList = new ListNode(0);
        ListNode oddTemp = oddNodeList, evenTemp = evenNodeList;
        while (head != null) {
            oddTemp.next = head;
            oddTemp = oddTemp.next;
            if (head.next==null){
                break;
            }
            evenTemp.next = head.next;
            evenTemp = evenTemp.next;
            head = head.next.next;
        }
        //合并之前需要把奇数和偶数位链表的尾结点置位null
        oddTemp.next=null;
        evenTemp.next=null;
        oddTemp.next=evenNodeList.next;
        return oddNodeList.next;
    }

    public static void main(String[] args) {
        ListNode node = oddEvenList(createLinkedList(1, 2, 3, 4, 5));
        System.out.println(node);
    }

}
